<template>
    <div class="edit-profile-page">
        <!-- 头部导航栏 -->
        <van-nav-bar title="编辑资料" left-text="" right-text="保存" left-arrow fixed placeholder @click-left="goBack"
            @click-right="saveProfile" />

        <!-- 用户信息编辑区域 -->
        <div class="profile-form">
            <van-cell-group>
                <van-field v-model="form.nickName" label="昵称" placeholder="请输入昵称" required />
                <van-field v-model="form.email" label="邮箱" placeholder="请输入邮箱" required />
                <van-field v-model="form.phone" label="手机号" placeholder="请输入手机号" required />
                <van-field name="sex" label="性别" :value="SEX_MAP[Number(form.sex) ?? 2]" @click="showSexPicker = true"
                    readonly placeholder="请选择性别" is-link />
                <van-field v-model="form.birthday" label="生日" placeholder="请选择生日" is-link readonly
                    @click="showBirthdayPicker = true" />
                <van-field v-model="form.areaName" label="地区" placeholder="请选择地区" is-link readonly
                    @click="showAreaPicker = true" />
            </van-cell-group>
        </div>

        <!-- 性别选择器 -->
        <van-popup v-model:show="showSexPicker" round position="bottom">
            <van-picker :columns="sexColumns" @confirm="onSexConfirm" @cancel="showSexPicker = false" />
        </van-popup>

        <!-- 生日选择器 -->
        <van-popup v-model:show="showBirthdayPicker" position="bottom">
            <van-date-picker title="选择生日" :min-date="minDate" :max-date="maxDate" @confirm="onBirthdayConfirm"
                @cancel="showBirthdayPicker = false" />
        </van-popup>

        <!-- 地区选择器 -->
        <van-popup v-model:show="showAreaPicker" position="bottom" round>
            <van-area title="选择地区" :area-list="areaList" @confirm="onAreaConfirm" @cancel="showAreaPicker = false" />
        </van-popup>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import type { User } from '@/models/user'
import { update } from "@/api/userInfo/index"

// 引入地区数据
import { areaList } from '@/utils/area/index'

const router = useRouter()

// 性别选项
const sexColumns = [
    { text: '男', value: 0 },
    { text: '女', value: 1 },
    { text: '保密', value: 2 }
]

const SEX_MAP: Record<number, string> = {
    0: '男',
    1: '女',
    2: '保密'
}




// 日期范围
const minDate = new Date(1900, 0, 1)
const maxDate = new Date()
const userInfoStr = localStorage.getItem('userInfo')
let user: User

try {
    user = userInfoStr ? JSON.parse(userInfoStr) : {} as User
} catch (error) {
    console.error('解析用户信息失败:', error)
    user = {} as User
}
// 表单数据
const form = reactive<Partial<User>>({
    userId: user.userId || '',
    nickName: user.nickName || '',
    email: user.email || '',
    phone: user.phone || '',
    sex: user.sex || '',
    areaName: user.areaName || '',   // 原来可能是 null，改为 ''
    areaCode: user.areaCode || '',   // 同上
    birthday: user.birthday || '',    // 同上
})

// 控制选择器显示
const showSexPicker = ref(false)
const showBirthdayPicker = ref(false)
const showAreaPicker = ref(false)


// 选择性别确认
const onSexConfirm = ({ selectedValues }: { selectedValues: number[] }) => {
    form.sex = selectedValues[0]
    showSexPicker.value = false
}

// 选择生日确认
const onBirthdayConfirm = ({ selectedValues }: { selectedValues: any[] }) => {
    const [year, month, day] = selectedValues
    form.birthday = `${year}-${month}-${day}`
    showBirthdayPicker.value = false
}

// 选择地区确认
const onAreaConfirm = ({ selectedOptions }: { selectedOptions: any[] }) => {
    form.areaName = selectedOptions.map((item: any) => item.text).join('/')
    form.areaCode = selectedOptions[selectedOptions.length - 1]?.value || ''
    showAreaPicker.value = false
}

// 返回上一页
const goBack = () => {
    router.back()
}

// 保存资料
const saveProfile = () => {
    if (!form.nickName || !form.email || !form.phone) {
        showToast('请填写必填信息')
        return
    }
    const saveData: User = {
        userId: form.userId ?? '',
        nickName: form.nickName,
        email: form.email,
        phone: form.phone,
        sex: form.sex ?? '',
        areaName: form.areaName ?? '',
        areaCode: form.areaCode ?? '',
        birthday: form.birthday ?? '',
        token: ''
    }
    console.log(form);
    update(saveData);

    showToast('保存成功')

    router.push('home')
}
</script>

<style scoped>
.edit-profile-page {
    background-color: #f5f5f5;
    min-height: 100vh;
}

.profile-form {
    margin-top: 12px;
}

:deep(.van-field__label) {
    width: 80px;
}
</style>